import http from '../api/http'
import type { ApiResult, PageRequest, PageResult } from './types'

// 优惠券模板相关类型定义
export interface CouponTemplate {
  id?: string
  templateCode?: string
  name: string
  schemeType: number // 1: 消费者承担服务费, 2: 商家承担服务费
  couponType: number // 1: 减免券, 2: 折扣券, 3: 礼品券
  discountAmount?: number // 减免金额（分）
  discount?: number // 折扣比例（0-1）
  useThresholdAmount?: number // 使用门槛金额（分）
  platformServiceFeeRate: number // 平台服务费率
  receiveStartTime: string // 领取开始时间
  receiveEndTime: string // 领取结束时间
  validityType: number // 有效期类型：1=固定时间范围，2=领取后N小时内可用
  validityStartTime?: string // 固定有效期开始时间
  validityEndTime?: string // 固定有效期结束时间
  validityDuration?: number // 有效期时长（小时）
  effectiveDelayType: number // 生效延迟类型：0=立即生效，1=次日0点生效，2=领取后N小时生效
  effectiveDelayValue?: number // 生效延迟值（小时）
  useFrequencyType: number // 使用频率限制：1=无限制，2=每日，3=每周
  useFrequencyLimit: number // 每个周期内最大使用次数
  total: number // 总数量
  usedCount?: number // 已使用数量
  maxIssuePerUser: number // 每人最多领取数量
  merchantId: string // 所属商户ID
  storeId?: string // 所属门店ID
  codeId?: string // 所属收款码ID
  posterUrl?: string // 海报地址
  extraProperties?: string // 扩展属性
  enableStatus?: number // 模板启用状态：0=禁用,1=启用
  creationTime?: string
  validityPeriod?: number // 有效期（天数）
  inventory?: number // 库存数量
  description?: string // 描述
  isActive?: boolean // 是否激活
  createdAt?: string // 创建时间
  updatedAt?: string // 更新时间
}

export interface CouponTemplateCreateRequest {
  id?: string
  name: string
  schemeType: number
  couponType: number
  discountAmount?: number
  discount?: number
  useThresholdAmount?: number
  platformServiceFeeRate: number
  receiveStartTime: string
  receiveEndTime: string
  validityType: number
  validityStartTime?: string
  validityEndTime?: string
  validityDuration?: number
  effectiveDelayType: number
  effectiveDelayValue?: number
  useFrequencyType: number
  useFrequencyLimit: number
  total: number
  maxIssuePerUser: number
  merchantId: string
  storeId?: string
  codeId?: string
  posterUrl?: string
  extraProperties?: string
  enableStatus?: number
  validityPeriod?: number
  inventory?: number
  description?: string
  isActive?: boolean
}

export interface CouponTemplateUpdateRequest extends CouponTemplateCreateRequest {
  id: string
}

export interface CouponTemplateQueryRequest extends PageRequest {
  templateCode?: string
  name?: string
  couponType?: number
  isActive?: boolean
  merchantId?: string
  storeId?: string
  codeId?: string
}

// 优惠券包相关类型定义
export interface CouponPackage {
  id?: string
  name: string
  description?: string
  couponTemplateIds: string[]
  validityPeriod?: number
  isActive?: boolean
  createdAt?: string
  updatedAt?: string
  receiveCount?: number
  couponCount?: number
  // 后端必填/重要字段（编辑时需要原样回传）
  status?: number
  enableStatus?: number
  startTime?: string
  endTime?: string
  qrcodeUrl?: string
  extraProperties?: string
  merchantId?: string
}

export interface CouponPackageCreateRequest {
  name: string
  description?: string
  couponTemplateIds: string[]
  validityPeriod?: number
  // 后端创建优惠券包所需字段（可选，按需传递）
  merchantId?: string
  startTime?: string
  endTime?: string
  status?: number
}

export interface CouponPackageUpdateRequest extends CouponPackageCreateRequest {
  id: string
  // 编辑更新时需要向后端传递的字段
  status?: number
  enableStatus?: number
  startTime?: string
  endTime?: string
  qrcodeUrl?: string
  extraProperties?: string
  merchantId?: string
}

export interface CouponPackageQueryRequest extends PageRequest {
  name?: string
  isActive?: boolean
}

// 优惠券实例相关类型定义
export interface CouponInstance {
  id?: string
  templateId: string
  templateName?: string
  userId?: string
  userPhone?: string
  status: number // 0: 未使用, 1: 已使用, 2: 已过期
  receivedAt?: string
  usedAt?: string
  expiredAt?: string
  orderId?: string
  orderNumber?: string
  discountAmount?: number
  createdAt?: string
}

export interface CouponInstanceQueryRequest extends PageRequest {
  templateId?: string
  userId?: string
  status?: number
  startDate?: string
  endDate?: string
}

// 优惠券消费记录类型定义
export interface CouponConsumptionRecord {
  id?: string
  couponInstanceId: string
  orderId: string
  orderNumber?: string
  orderAmount?: number
  discountAmount: number
  consumedAt: string
  userId?: string
  userPhone?: string
}

export interface CouponConsumptionQueryRequest extends PageRequest {
  couponInstanceId?: string
  orderId?: string
  userId?: string
  startDate?: string
  endDate?: string
}

// 券包领取记录类型与查询请求
export interface CouponPackageReceiveRecord {
  id?: string
  userId?: string
  receiveChannel?: number | string
  receiveCode?: string
  ipaddress?: string
  deviceInfo?: string
  packageId?: string
  receivedAt?: string
}

export interface CouponPackageReceiveQueryRequest extends PageRequest {
  packageId: string
}

// 优惠券计算请求和响应
export interface CouponCalculateRequest {
  templateId: string
  orderAmount: number // 订单金额（分）
}

export interface CouponCalculateResponse {
  canUse: boolean
  discountAmount: number
  finalAmount: number
  reason?: string
}

// 统计数据接口
export interface CouponStatistics {
  totalTemplates: number
  activeTemplates: number
  totalIssued: number
  totalUsed: number
  totalExpired: number
  totalDiscountAmount: number
}

// API 服务类
export class CouponService {
  // 优惠券模板管理
  static async createTemplate(data: CouponTemplateCreateRequest): Promise<ApiResult<string>> {
    const response = await http.post<ApiResult<string>>('/Coupon/AddCouponTemplate', data)
    return response.data
  }

  static async updateTemplate(data: CouponTemplateUpdateRequest): Promise<ApiResult<boolean>> {
    const response = await http.post<ApiResult<boolean>>('/Coupon/UpdateCouponTemplate', data)
    return response.data
  }

  static async deleteTemplate(id: string): Promise<ApiResult<boolean>> {
    const response = await http.post<ApiResult<boolean>>('/Coupon/DeleteCouponTemplate', { id })
    return response.data
  }

  static async getTemplateDetail(id: string): Promise<ApiResult<CouponTemplate>> {
    const response = await http.get<ApiResult<CouponTemplate>>(`/Coupon/GetCouponTemplateDetail?id=${id}`)
    return response.data
  }

  static async getTemplateList(params: CouponTemplateQueryRequest): Promise<ApiResult<PageResult<CouponTemplate>>> {
    const response = await http.get<ApiResult<PageResult<CouponTemplate>>>('/Coupon/GetCouponTemplateList', { params })
    return response.data
  }

  static async queryTemplates(params: CouponTemplateQueryRequest): Promise<ApiResult<PageResult<CouponTemplate>>> {
    return this.getTemplateList(params)
  }

  static async increaseInventory(templateId: string, amount: number): Promise<ApiResult<boolean>> {
    const response = await http.post<ApiResult<boolean>>('/Coupon/IncreaseCouponTemplateInventory', {
      TemplateId: templateId,
      IncreaseAmount: amount
    })
    return response.data
  }

  // 统计数据接口
  static async getStatistics(): Promise<ApiResult<CouponStatistics>> {
    // 注意：这里需要根据实际后端接口调整，目前后端可能没有统一的统计接口
    // 可能需要通过多个接口组合获取统计数据
    const response = await http.get<ApiResult<CouponStatistics>>('/Coupon/GetCouponStatistics')
    return response.data
  }

  // 优惠券包管理
  static async createPackage(data: CouponPackageCreateRequest): Promise<ApiResult<string>> {
    const payload: any = { ...data, ids: data.couponTemplateIds }
    const response = await http.post<ApiResult<string>>('/Coupon/AddCouponPackage', payload)
    return response.data
  }

  static async updatePackage(data: CouponPackageUpdateRequest): Promise<ApiResult<boolean>> {
    const payload: any = { ...data, ids: data.couponTemplateIds }
    const response = await http.post<ApiResult<boolean>>('/Coupon/UpdateCouponPackage', payload)
    return response.data
  }

  static async deletePackage(id: string): Promise<ApiResult<boolean>> {
    const response = await http.post<ApiResult<boolean>>('/Coupon/DeleteCouponPackage', { id })
    return response.data
  }

  static async getPackage(id: string): Promise<ApiResult<CouponPackage>> {
    const response = await http.post<ApiResult<any>>('/Coupon/GetCouponPackage', { id })
    const res = response.data
    if (res?.code === 0 && res.data) {
      const d = res.data
      const ids: string[] = Array.isArray(d.ids)
        ? d.ids
        : Array.isArray(d.couponPackageItems)
          ? d.couponPackageItems.map((x: any) => x?.templateId).filter(Boolean)
          : []

      const normalized: CouponPackage = {
        id: d.id,
        name: d.name,
        description: d.description,
        couponTemplateIds: ids,
        validityPeriod: undefined,
        isActive: d.enableStatus === 1,
        createdAt: d.creationTime,
        updatedAt: d.creationTime,
        receiveCount: 0,
        couponCount: ids.length,
        // 保留后端返回的关键字段，供更新时原样传递
        status: d.status,
        enableStatus: d.enableStatus,
        startTime: d.startTime,
        endTime: d.endTime,
        qrcodeUrl: d.qrcodeUrl,
        extraProperties: d.extraProperties,
        merchantId: d.merchantId
      }

      return { code: res.code, message: res.message, data: normalized }
    }
    return res
  }

  static async getPackageList(params: CouponPackageQueryRequest): Promise<ApiResult<PageResult<CouponPackage>>> {
    const response = await http.get<ApiResult<PageResult<any>>>('/Coupon/GetCouponPackageList', { params })
    const res = response.data
    if (res?.code === 0 && res.data) {
      const { total, data } = res.data
      const normalized: PageResult<CouponPackage> = {
        total: total || 0,
        data: Array.isArray(data)
          ? data.map((d: any) => ({
              id: d.id,
              name: d.name,
              description: d.description,
              couponTemplateIds: Array.isArray(d.ids) ? d.ids : [],
              validityPeriod: undefined,
              isActive: d.enableStatus === 1,
              createdAt: d.creationTime,
              updatedAt: d.lastModificationTime || d.creationTime,
              receiveCount: d.issueCount || 0,
              couponCount: Array.isArray(d.ids) ? d.ids.length : 0,
              // 保留关键字段以便后续编辑页使用
              status: d.status,
              enableStatus: d.enableStatus,
              startTime: d.startTime,
              endTime: d.endTime,
              qrcodeUrl: d.qrcodeUrl,
              extraProperties: d.extraProperties,
              merchantId: d.merchantId
            }))
          : []
      }
      return { code: res.code, message: res.message, data: normalized }
    }
    return res as ApiResult<PageResult<CouponPackage>>
  }

  // 优惠券实例管理
  static async getUserCouponList(params: CouponInstanceQueryRequest): Promise<ApiResult<PageResult<CouponInstance>>> {
    const response = await http.get<ApiResult<PageResult<CouponInstance>>>('/Coupon/GetUserCouponInstanceList', { params })
    return response.data
  }

  static async getConsumptionRecords(params: CouponConsumptionQueryRequest): Promise<ApiResult<PageResult<CouponConsumptionRecord>>> {
    const response = await http.get<ApiResult<PageResult<CouponConsumptionRecord>>>('/Coupon/GetCouponConsumptionRecordList', { params })
    return response.data
  }

  // 券包领取记录查询
  static async getPackageReceiveRecords(params: CouponPackageReceiveQueryRequest): Promise<ApiResult<PageResult<CouponPackageReceiveRecord>>> {
    const response = await http.get<ApiResult<PageResult<any>>>('/Coupon/GetCouponPackageReceiveRecordList', { params })
    const res = response.data
    if (res?.code === 0 && res.data) {
      const { total, data } = res.data
      const normalized: PageResult<CouponPackageReceiveRecord> = {
        total: total || 0,
        data: Array.isArray(data)
          ? data.map((r: any) => ({
              id: r.id,
              userId: r.userId,
              receiveChannel: r.receiveChannel,
              receiveCode: r.receiveCode,
              ipaddress: r.ipaddress,
              deviceInfo: r.deviceInfo,
              packageId: r.packageId,
              receivedAt: r.creationTime
            }))
          : []
      }
      return { code: res.code, message: res.message, data: normalized }
    }
    return res
  }

  // 优惠券计算
  static async calculateCoupon(couponInstanceId: string, orderAmount: number): Promise<ApiResult<CouponCalculateResponse>> {
    const response = await http.get<ApiResult<CouponCalculateResponse>>(`/Coupon/CalculateCouponInstance?couponInstanceId=${couponInstanceId}&orderAmount=${orderAmount}`)
    return response.data
  }

  // 优惠券发放和使用
  static async receivePackage(packageId: string, userId: string): Promise<ApiResult<boolean>> {
    const response = await http.post<ApiResult<boolean>>('/Coupon/ReceiveCouponPackage', {
      packageId,
      userId
    })
    return response.data
  }

  static async userGetCoupon(data: { TemplateId: string, UserId?: string }): Promise<ApiResult<boolean>> {
    const response = await http.post<ApiResult<boolean>>('/Coupon/UserGetCoupon', data)
    return response.data
  }

  static async redeemGiftCoupon(data: { GiftCode: string, UserId?: string }): Promise<ApiResult<boolean>> {
    const response = await http.post<ApiResult<boolean>>('/Coupon/RedeemGiftCoupon', data)
    return response.data
  }

  static async cancelConsumption(couponInstanceId: string, orderId: string): Promise<ApiResult<boolean>> {
    const response = await http.get<ApiResult<boolean>>(`/Coupon/CancelCouponConsumption?couponInstanceId=${couponInstanceId}&orderId=${orderId}`)
    return response.data
  }

  // 平台推送优惠券
  static async platformPushCoupon(page: number = 1, limit: number = 5, merchantId?: string, storeId?: string): Promise<ApiResult<any>> {
    const response = await http.get<ApiResult<any>>(`/Coupon/PlatformRandomlyPusheCoupon?page=${page}&limit=${limit}&merchantId=${merchantId || ''}&storeId=${storeId || ''}`)
    return response.data
  }

  // 获取优惠券实例详情
  static async getCouponInstanceDetail(couponInstanceId: string): Promise<ApiResult<any>> {
    const response = await http.get<ApiResult<any>>(`/Coupon/GetCouponInstanceDetail?couponInstanceId=${couponInstanceId}`)
    return response.data
  }

  // 获取优惠券实例列表
  static async getCouponInstanceList(page: number = 1, limit: number = 10, templateId?: string, userId?: string, status?: number): Promise<ApiResult<any>> {
    const params = new URLSearchParams({
      page: page.toString(),
      limit: limit.toString()
    })
    if (templateId) params.append('templateId', templateId)
    if (userId) params.append('userId', userId)
    if (status !== undefined) params.append('status', status.toString())
    
    const response = await http.get<ApiResult<any>>(`/Coupon/GetCouponInstanceList?${params.toString()}`)
    return response.data
  }

  // 获取优惠券包详情
  static async getCouponPackageDetail(packageId: string): Promise<ApiResult<any>> {
    const response = await http.get<ApiResult<any>>(`/Coupon/GetCouponPackageDetail?packageId=${packageId}`)
    return response.data
  }

  // 获取优惠券包列表
  static async getCouponPackageList(page: number = 1, limit: number = 10, merchantId?: string, storeId?: string): Promise<ApiResult<any>> {
    const params = new URLSearchParams({
      page: page.toString(),
      limit: limit.toString()
    })
    if (merchantId) params.append('merchantId', merchantId)
    if (storeId) params.append('storeId', storeId)
    
    const response = await http.get<ApiResult<any>>(`/Coupon/GetCouponPackageList?${params.toString()}`)
    return response.data
  }

  // 创建优惠券包
  static async createCouponPackage(data: CouponPackageCreateRequest): Promise<ApiResult<boolean>> {
    const response = await http.post<ApiResult<boolean>>('/Coupon/CreateCouponPackage', data)
    return response.data
  }

  // 更新优惠券包
  static async updateCouponPackage(data: CouponPackageUpdateRequest): Promise<ApiResult<boolean>> {
    const response = await http.put<ApiResult<boolean>>('/Coupon/UpdateCouponPackage', data)
    return response.data
  }

  // 删除优惠券包
  static async deleteCouponPackage(packageId: string): Promise<ApiResult<boolean>> {
    const response = await http.delete<ApiResult<boolean>>(`/Coupon/DeleteCouponPackage?packageId=${packageId}`)
    return response.data
  }

  // 获取优惠券统计信息
  static async getCouponStatistics(templateId?: string, startDate?: string, endDate?: string): Promise<ApiResult<any>> {
    const params = new URLSearchParams()
    if (templateId) params.append('templateId', templateId)
    if (startDate) params.append('startDate', startDate)
    if (endDate) params.append('endDate', endDate)
    
    const response = await http.get<ApiResult<any>>(`/Coupon/GetCouponStatistics?${params.toString()}`)
    return response.data
  }

  // 获取优惠券消费记录
  static async getCouponConsumptionRecords(page: number = 1, limit: number = 10, couponInstanceId?: string, orderId?: string): Promise<ApiResult<any>> {
    const params = new URLSearchParams({
      page: page.toString(),
      limit: limit.toString()
    })
    if (couponInstanceId) params.append('couponInstanceId', couponInstanceId)
    if (orderId) params.append('orderId', orderId)
    
    const response = await http.get<ApiResult<any>>(`/Coupon/GetCouponConsumptionRecords?${params.toString()}`)
    return response.data
  }
}

// 导出常用的枚举和常量
export const CouponSchemeType = {
  CONSUMER_BEAR: 1, // 消费者承担服务费
  MERCHANT_BEAR: 2  // 商家承担服务费
} as const

export const CouponType = {
  REDUCTION: 1, // 减免券
  DISCOUNT: 2,  // 折扣券
  GIFT: 3       // 礼品券
} as const

export const CouponStatus = {
  UNUSED: 1,    // 未使用
  USED: 2,      // 已使用
  EXPIRED: 3    // 已过期
} as const

export const ValidityType = {
  FIXED_PERIOD: 1, // 固定时间范围
  DURATION_AFTER_RECEIVE: 2 // 领取后N小时内可用
} as const

export const EffectiveDelayType = {
  IMMEDIATE: 0, // 立即生效
  NEXT_DAY: 1,  // 次日0点生效
  AFTER_HOURS: 2 // 领取后N小时生效
} as const

export const UseFrequencyType = {
  UNLIMITED: 1, // 无限制
  DAILY: 2,     // 每日
  WEEKLY: 3     // 每周
} as const

// 工具函数
export const formatCouponAmount = (amount: number): string => {
  return `¥${(amount / 100).toFixed(2)}`
}

export const formatCouponDiscount = (discount: number): string => {
  return `${(discount * 10).toFixed(1)}折`
}

export const getCouponTypeText = (type: number): string => {
  switch (type) {
    case CouponType.REDUCTION:
      return '减免券'
    case CouponType.DISCOUNT:
      return '折扣券'
    case CouponType.GIFT:
      return '礼品券'
    default:
      return '未知类型'
  }
}

export const getCouponStatusText = (status: number): string => {
  switch (status) {
    case CouponStatus.UNUSED:
      return '未使用'
    case CouponStatus.USED:
      return '已使用'
    case CouponStatus.EXPIRED:
      return '已过期'
    default:
      return '未知状态'
  }
}

export const getCouponStatusColor = (status: number): string => {
  switch (status) {
    case CouponStatus.UNUSED:
      return 'var(--success)'
    case CouponStatus.USED:
      return 'var(--info)'
    case CouponStatus.EXPIRED:
      return 'var(--text-muted)'
    default:
      return 'var(--text-muted)'
  }
}

export const getSchemeTypeText = (type: number): string => {
  switch (type) {
    case CouponSchemeType.CONSUMER_BEAR:
      return '消费者承担服务费'
    case CouponSchemeType.MERCHANT_BEAR:
      return '商家承担服务费'
    default:
      return '未知方案'
  }
}

export const getValidityTypeText = (type: number): string => {
  switch (type) {
    case ValidityType.FIXED_PERIOD:
      return '固定时间范围'
    case ValidityType.DURATION_AFTER_RECEIVE:
      return '领取后N小时内可用'
    default:
      return '未知有效期类型'
  }
}
